<?php

class ProjectController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
				'rights',
			//'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','getActiveProject','teacherView','studentView'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionGetActiveProject($id)
	{
		$student=Student::model()->findByPk($id);
		$data=array(
				'projectID'=>$student->activeProject->projectID,
		);
		echo json_encode($data);
	}
	public function actionView($id)
	{
		$regTeacher1=new UserAccount();
		$regTeacher2=new UserAccount();
		$regTeacher3=new UserAccount();
		$commit1=new Committee();
		$commit2=new Committee();
		$commit3=new Committee();
		$model=$this->loadModel($id);
		if (sizeof($exam=$model->exams)){
		if ($model->statusCode=="step7"||$model->statusCode=="step8"||$model->statusCode=="step9"||$model->statusCode=="step10"||$model->statusCode=="step11") {
			$exam=$model->exams[1];
		}else{
			$exam=$model->exams[0];
		}
		}
		if (!$exam){
		$exam=new Exam();
		}
		$newExam=new Exam();
		if(isset($_POST['ajax']) && ($_POST['ajax']==='project-form')){
		$this->performAjaxValidation($model);
		}elseif(isset($_POST['ajax']) && ($_POST['ajax']==='exam-form')){
		$this->performAjaxValidation($newExam);
		}
		if (isset($_POST['Exam'])){
			if (!isset($_POST['Exam']['resultDate'])) {
			$newExam->attributes=$_POST['Exam'];
			$newExam->examDate=DateTimeArray::convertThaiDateToMysql($newExam->examDate);
			$newExam->projectID=$id;
			$transaction=$newExam->dbConnection->beginTransaction();
			if ($newExam->save()){
				if ($_POST["commitTypeID"][0]=='1') {
					if ($_POST['user_id1']){
					$regTeacher1->user_id=$_POST['user_id1'];
					$regTeacher1->name=$_POST['name1'];
					$teacher1=Teacher::model()->findByPk($regTeacher1->user_id);
					if (!$teacher1){
						$teacher1=new Teacher();
						$teacher1->teacherID=$regTeacher1->user_id;
							
					}
					$teacher1->active="Y";
					$teacher1->save();
				
					$commit1->commitTypeID=1;
					$commit1->teacherID=$teacher1->teacherID;
					$commit1->examID=$newExam->examID;
					$commit1->save();
				}
					
				}else{
				
					$commit1->commitTypeID=2;
					$commit1->title=$_POST['title1'];
					$commit1->name=$_POST['cname1'];
					//$commit1->teacherID=CDbExpression('NULL');
					$commit1->examID=$newExam->examID;
					$commit1->save();
				}
				if ($_POST["commitTypeID"][1]=='1') {
					if ($_POST['user_id2']){
					$regTeacher2->user_id=$_POST['user_id2'];
					$regTeacher2->name=$_POST['name2'];
					$teacher2=Teacher::model()->findByPk($regTeacher2->user_id);
					if (!$teacher2){
						$teacher2=new Teacher();
						$teacher2->teacherID=$regTeacher2->user_id;
							
					}
					$teacher2->active="Y";
					$teacher2->save();
				
					$commit2->commitTypeID=1;
					$commit2->teacherID=$teacher2->teacherID;
					$commit2->examID=$newExam->examID;
					$commit2->save();
				}
				}else{
				
					$commit2->commitTypeID=2;
					$commit2->title=$_POST['title2'];
					$commit2->name=$_POST['cname2'];
					//$commit2->teacherID=CDbExpression('NULL');
					$commit2->examID=$newExam->examID;
					$commit2->save();
				}
				if ($_POST["commitTypeID"][2]=='1') {
					if ($_POST['user_id3']){
					$regTeacher3->user_id=$_POST['user_id3'];
					$regTeacher3->name=$_POST['name3'];
					$teacher3=Teacher::model()->findByPk($regTeacher3->user_id);
					if (!$teacher3){
						$teacher3=new Teacher();
						$teacher3->teacherID=$regTeacher3->user_id;
							
					}
					$teacher3->active="Y";
					$teacher3->save();
				
					$commit3->commitTypeID=1;
					$commit3->teacherID=$teacher3->teacherID;
					$commit3->examID=$newExam->examID;
					$commit3->save();
					}
				}else{
				
					$commit3->commitTypeID=2;
					$commit3->title=$_POST['title3'];
					//$commit3->teacherID=CDbExpression('NULL');
					$commit3->name=$_POST['cname3'];
					$commit3->examID=$newExam->examID;
					$commit3->save();
				}
				
				$step=new ProjectStatus;
				
				if ($model->statusCode=='step6') {
					$step->statusCode="step7";
					$oldStep='step6';
				}
				else{
				$step->statusCode="step2";
				$oldStep='step1';
				}
				$step->startDate=new CDbExpression('NOW()');
				$step->projectID=$model->projectID;
				$step->save();
				
				$model->statusCode=$step->statusCode;
				
				$model->save();
				if (sizeof($newExam->committees)==3){
				$transaction->commit();
				$exam=$newExam;
				}else{
					$transaction->rollback();
					$model->statusCode=$oldStep;
				}
			}
			}else{
				//exit;
				$exam->attributes=$_POST['Exam'];
				$exam->resultDate=DateTimeArray::convertThaiDateToMysql($exam->resultDate);
				//$exam->resultDate=$exam->resultDate;
				$exam->projectID=$id;
				if ($exam->save()){
					$step=new ProjectStatus;
					if ($model->statusCode=='step2') {
					if ($exam->examResult=='Y'){
					if ($exam->criteria=='Y') {
					$step->statusCode="step4";
					}else{
						$step->statusCode="step3";
					}
					}else{
						$step->statusCode="step6";
					}
					}else{
						if ($exam->examResult=='Y'){
							if ($exam->criteria=='Y') {
								$step->statusCode="step9";
							}else{
								$step->statusCode="step8";
							}
						}else{
							$step->statusCode="step11";
						}	
					}
					$step->startDate=new CDbExpression('NOW()');
					$step->projectID=$model->projectID;
					$step->save();
					$model->statusCode=$step->statusCode;
					$model->save();
				}
			}	
		}
		$this->render('view',array(
				'model'=>$model,
				'exam'=>$exam,
				//'submodel'=>$submodel,
				'regTeacher1'=>$regTeacher1,
				'regTeacher2'=>$regTeacher2,
				'regTeacher3'=>$regTeacher3,
				'commit1'=>$commit1,
				'commit2'=>$commit2,
				'commit3'=>$commit3,
				'newExam'=>$newExam,
		));
	}
	public function actionTeacherView($id)
	{
		$regTeacher1=new UserAccount();
		$regTeacher2=new UserAccount();
		$regTeacher3=new UserAccount();
		$commit1=new Committee();
		$commit2=new Committee();
		$commit3=new Committee();
		$model=$this->loadModel($id);
		if (sizeof($exam=$model->exams)){
			$exam=$model->exams[0];
		}
		if (!$exam){
			$exam=new Exam();
		}
		$this->render('teacherView',array(
				'model'=>$model,
				'exam'=>$exam,
				//'submodel'=>$submodel,
				'regTeacher1'=>$regTeacher1,
				'regTeacher2'=>$regTeacher2,
				'regTeacher3'=>$regTeacher3,
				'commit1'=>$commit1,
				'commit2'=>$commit2,
				'commit3'=>$commit3,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($id=null)
	{
		$model=new Project;
		$regTeacher1=new UserAccount();
		$regTeacher2=new UserAccount();
		$student=new Student();
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
		
		if ($id) {
			$regStudent=RegStudent::model()->findByPk($id);
			$regStudent->student_name=$regStudent->student_name." ".$regStudent->student_surname;
		}else{
			$regStudent=new RegStudent();
		}
		if(isset($_POST['Project']))
		{
			
			
			//$regStudent->attributes=$_POST['RegStudent'];
			$regStudent=RegStudent::model()->findByPk($_POST['RegStudent']['student_id']);
			$regStudent->student_name=$regStudent->student_name." ".$regStudent->student_surname;
			$checkProject=Project::model()->findAllByAttributes(array('studentID'=>$regStudent->student_id,'active'=>'Y'));
			if ($checkProject) {
				Yii::app()->user->setFlash('error', "นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว!");
				$this->render('error',array(
						//'errorMessage'=>'นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว',
				));
				exit();
			}
			if ($regStudent->gpa<3){
				Yii::app()->user->setFlash('error', "นักศึกษามีเกรดเฉลี่ยสะสมยังไม่ถึง 3.00!");
				$this->render('error',array(
						//'errorMessage'=>'นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว',
				));
				exit();
			}
			if ($regStudent->sum_credit<12){
				Yii::app()->user->setFlash('error', "นักศึกษามีหน่วยกิตสะสมยังไม่ถึง 12 หน่วยกิต!");
				$this->render('error',array(
						//'errorMessage'=>'นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว',
				));
				exit();
			}
			$student=Student::model()->findByPk($regStudent->student_id);
			if (!$student){
			$student=new Student();
			$student->studentID=$regStudent->student_id;
			}
			$student->active='Y'; 
			
			$model->attributes=$_POST['Project'];
			$model->studentID=$regStudent->student_id;
			$model->active='Y';
			$model->createUser=Yii::app()->user->id;
			$model->createDate=new CDbExpression('NOW()');
			$model->startDate=DateTimeArray::convertThaiDateToMysql($model->startDate);
			if ($_POST['majorAdvisorID']!=$_POST['minorAdvisorID']){
			$regTeacher1->user_id=$_POST['majorAdvisorID'];
			$regTeacher1->name=$_POST['majorAdvisor'];
			$regTeacher2->user_id=$_POST['minorAdvisorID'];
			$regTeacher2->name=$_POST['minorAdvisor'];
			}
			$transaction=$student->dbConnection->beginTransaction();
			$teacher1=Teacher::model()->findByPk($regTeacher1->user_id);
			$teacher2=Teacher::model()->findByPk($regTeacher2->user_id);
			if (!$teacher1) {
			$teacher1=new Teacher();
			$teacher1->teacherID=$regTeacher1->user_id;
			}
			if (!$teacher2) {
			$teacher2=new Teacher();
			$teacher2->teacherID=$regTeacher2->user_id;
			}
			$teacher1->active="Y";
			$teacher2->active="Y";
			$teacher1->save();
			$data[]=$teacher1;
			if ($regTeacher2->user_id){
			$teacher2->save();
			$data[]=$teacher2;
			}
			$model->teachers=$data;
			if($student->save()){
				if ($model->save()){
					$step=new ProjectStatus;
					$step->statusCode="step1";
					$step->startDate=new CDbExpression('NOW()');
					$step->projectID=$model->projectID;	
					$step->save();
					$model->statusCode=$step->statusCode;
					$model->save();
					$transaction->commit();
				$this->redirect(array('view','id'=>$model->projectID));
				}else{
				$transaction->rollback();
				}
			}
		}

		$this->render('create',array(
			'model'=>$model,
			'regStudent'=>$regStudent,
			'teacher1'=>$regTeacher1,
			'teacher2'=>$regTeacher2,
			'student'=>$student,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$model->startDate=DateTimeArray::convertMysqlToThai($model->startDate);
		$regStudent=RegStudent::model()->findByPk($model->student->studentID);
		$regStudent->student_name=$regStudent->student_name." ".$regStudent->student_surname;
		$student=$model->student;
		$regTeacher1=UserAccount::model()->findByPk($model->teachers[0]->teacherID);
		$regTeacher1->name=$regTeacher1->name." ".$regTeacher1->surname; 
		if (isset($model->teachers[1])) {
			$regTeacher2=UserAccount::model()->findByPk($model->teachers[1]->teacherID);
			$regTeacher2->name=$regTeacher2->name." ".$regTeacher2->surname;
		}
		//print_r($regStudent);
		//exit();
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

	if(isset($_POST['Project']))
		{
			
			
			//$regStudent->attributes=$_POST['RegStudent'];
			$regStudent=RegStudent::model()->findByPk($_POST['RegStudent']['student_id']);
			$regStudent->student_name=$regStudent->student_name." ".$regStudent->student_surname;
			$checkProject=Project::model()->findAllByAttributes(array('studentID'=>$regStudent->student_id,'active'=>'Y'),'projectID!=:projectID',array('projectID'=>$model->projectID));
			if ($checkProject) {
				Yii::app()->user->setFlash('error', "นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว!");
				$this->render('error',array(
						//'errorMessage'=>'นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว',
				));
				exit();
			}
			if ($regStudent->gpa<3){
				Yii::app()->user->setFlash('error', "นักศึกษามีเกรดเฉลี่ยสะสมยังไม่ถึง 3.00!");
				$this->render('error',array(
						//'errorMessage'=>'นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว',
				));
				exit();
			}
			if ($regStudent->sum_credit<12){
				Yii::app()->user->setFlash('error', "นักศึกษามีหน่วยกิตสะสมยังไม่ถึง 12 หน่วยกิต!");
				$this->render('error',array(
						//'errorMessage'=>'นักศึกษามีโปรเจคที่ต้องดำเนินการแล้ว',
				));
				exit();
			}
			$student=Student::model()->findByPk($regStudent->student_id);
			if (!$student){
			$student=new Student();
			$student->studentID=$regStudent->student_id;
			}
			$student->active='Y'; 
			
			$model->attributes=$_POST['Project'];
			$model->studentID=$regStudent->student_id;
			$model->active='Y';
			$model->createUser=Yii::app()->user->id;
			$model->createDate=new CDbExpression('NOW()');
			$model->startDate=DateTimeArray::convertThaiDateToMysql($model->startDate);
			if ($_POST['majorAdvisorID']!=$_POST['minorAdvisorID']){
			$regTeacher1->user_id=$_POST['majorAdvisorID'];
			$regTeacher1->name=$_POST['majorAdvisor'];
			$regTeacher2->user_id=$_POST['minorAdvisorID'];
			$regTeacher2->name=$_POST['minorAdvisor'];
			}
			$transaction=$student->dbConnection->beginTransaction();
			$teacher1=Teacher::model()->findByPk($regTeacher1->user_id);
			$teacher2=Teacher::model()->findByPk($regTeacher2->user_id);
			if (!$teacher1) {
			$teacher1=new Teacher();
			$teacher1->teacherID=$regTeacher1->user_id;
			}
			if (!$teacher2) {
			$teacher2=new Teacher();
			$teacher2->teacherID=$regTeacher2->user_id;
			}
			$teacher1->active="Y";
			$teacher2->active="Y";
			$teacher1->save();
			$data[]=$teacher1;
			if ($regTeacher2->user_id){
			$teacher2->save();
			$data[]=$teacher2;
			}
			$model->teachers=$data;
			if($student->save()){
				if ($model->save()){
					$step=new ProjectStatus;
					$step->statusCode="step1";
					$step->startDate=new CDbExpression('NOW()');
					$step->projectID=$model->projectID;	
					$step->save();
					$model->statusCode=$step->statusCode;
					$model->save();
					$transaction->commit();
				$this->redirect(array('view','id'=>$model->projectID));
				}else{
				$transaction->rollback();
				}
			}
		}

		$this->render('update',array(
			'model'=>$model,
			'regStudent'=>$regStudent,
			'teacher1'=>$regTeacher1,
			'teacher2'=>$regTeacher2,
			'student'=>$student,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Project');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Project('search');
		$student=new Student();
		$regStudent=new RegStudent();
		$student->regStudent=$regStudent;
		$model->student=$student;
		/* if($tid){
			$teacher=Teacher::model()->findByPk($tid);
			if ($teacher){
			if ($type=="teacher"){
				$teachers[]=$teacher;
				$commitee=new Committee();
				$committees[]=$commitee;
			}elseif ($type=="committee"){
				$commitee=new Committee();
				$commitee->teacherID=$teacher->teacherID;
				$committees[]=$commitee;
				$teacher=new Teacher();
				$teachers[]=$teacher;
			}
			}else{
				$teacher=new Teacher();
				$commitee=new Committee();
				$teachers[]=$teacher;
				$committees[]=$commitee;
			}
		}else{
			$teacher=new Teacher();
			$commitee=new Committee();
			$teachers[]=$teacher;
			$committees[]=$teacher;
		}
		$exam=new Exam();
		$exam->committees=$committees;
		$exams[]=$exam;
		$model->teachers=$teachers;
		$model->exams=$exams; */
		//$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Project'])){
			$model->attributes=$_GET['Project'];
			if (isset($_GET['RegStudent'])) {
			$regStudent->attributes=$_GET['RegStudent'];
			$student->regStudent=$regStudent;
			$model->student=$student;
			}
		}

		$this->render('admin',array(
			'model'=>$model,
			'regStudent'=>$regStudent,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Project the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Project::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Project $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && ($_POST['ajax']==='project-form')||($_POST['ajax']==='exam-form'))
		{
			
			echo CActiveForm::validate($model);
			Yii::app()->end();
			
	
		}
	}
}
